package com.example.mysqlite.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.AbstractWindowedCursor;
import android.database.Cursor;
import android.database.CursorWindow;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

import com.example.mysqlite.dto.Student;
import com.example.mysqlite.util.DBhelpUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

public class StudentDao {
    private DBhelpUtil dBhelpUtil;


    /**相当于获得一个链接数据库的对象*/
    private SQLiteDatabase DB;
    private Context context;
    public StudentDao(Context context,DBhelpUtil dBhelpUtil){
        this.context =context;
        this.dBhelpUtil = dBhelpUtil;
    }
    //保存数据
    public Long save(Student student) {
        /** 获取一个写 操作数据的对象*/
        DB = dBhelpUtil.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put(DBhelpUtil.TB_NAME,student.name);
        contentValues.put(DBhelpUtil.TB_SEX,student.sex);
        contentValues.put(DBhelpUtil.TB_AGE,student.age);
        contentValues.put(DBhelpUtil.TB_CLAZZ,student.clazz);

//        Log.e("TAG","--------------"+student.toString());
//        Toast.makeText(context,"sql 语句--"+student.toString(),Toast.LENGTH_LONG).show();
        //时间
        Date date = new Date();
        //格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        contentValues.put(DBhelpUtil.TB_CREATEDATE, simpleDateFormat.format(date));


        /**insert()
         * String table: 表名
         * String nullColumnHack： 不允许插入空行，为了防止插入空行，可以在这里随便指定一列， 如果有空值插入 会用null表示，好像没作用~
         * ContentValues values 数据行数据
         * 返回值 成功插入行号的id  ,插入失败 -1
         */
        return DB.insert(DBhelpUtil.TABLE_NAME,"空值",contentValues);
        //INSERT INTO tb_student(id,age,sex,name,clazz,createDate) VALUES (?,?,?,?,?,?)

    }

    /**查询数据*/
    public List<Student> select(Long id) {
        /** 获取一个读 操作数据的对象*/
        DB =dBhelpUtil.getReadableDatabase();

        /**query() 查询数据
         *String table, 表名
         * String[] columns, 要查询要显示的列
         * String selection,   查询条件
         * String[] selectionArgs, 参数值
         * String groupBy, 分组
         * String having, 分组后的条件
         * String orderBy 排序
         * 返回游标 Cursor
          */
        String[] columns = new String[]{
                "id",
                DBhelpUtil.TB_NAME,
                DBhelpUtil.TB_SEX,
                DBhelpUtil.TB_AGE,
                DBhelpUtil.TB_CLAZZ,
                DBhelpUtil.TB_CREATEDATE
        };
        Cursor cursor = null;
        if(id == null){
            //全查
             cursor = DB.query(DBhelpUtil.TABLE_NAME,columns,null,null,null,null,"id desc");
        }else {
            //根据id 查询
            cursor = DB.query(DBhelpUtil.TABLE_NAME,columns,"id=?",new String[]{String.valueOf(id)},null,null,null);

        }

        List<Student> studentList = new ArrayList<>();
        if(cursor != null){
            //遍历游标
            while(cursor.moveToNext()){
                Student student = new Student();
                // 根据游标找到列  在获取数据
                student.id = cursor.getLong(cursor.getColumnIndexOrThrow("id"));
                student.name = cursor.getString(cursor.getColumnIndexOrThrow(DBhelpUtil.TB_NAME));
                student.sex = cursor.getString(cursor.getColumnIndexOrThrow(DBhelpUtil.TB_SEX));
                student.age = cursor.getInt(cursor.getColumnIndexOrThrow(DBhelpUtil.TB_AGE));
                student.clazz = cursor.getString(cursor.getColumnIndexOrThrow(DBhelpUtil.TB_CLAZZ));
                student.creatDate = cursor.getString(cursor.getColumnIndexOrThrow(DBhelpUtil.TB_CREATEDATE));

                //添加到集合
                studentList.add(student);
            }
        }

        cursor.close();

        return studentList;
    }
    /**删除数据*/
    public int delete(Long id) {
        // 获取操作数据库对象
        DB = dBhelpUtil.getWritableDatabase();

        /**
         * String table,  表名
         * String whereClause, 条件
         * String[] whereArgs 参数
         * 返回影响行数，失败 0
         */
        //全部删除
        if(id == null){
            return DB.delete(DBhelpUtil.TABLE_NAME,null,null);
        }
        // 条件查询
       return DB.delete(DBhelpUtil.TABLE_NAME,"id = ?",new String[]{id+""});
    }

    /**保存位图*/
    public void saveBitmap(Student student) {
        /** 获取一个写 操作数据的对象*/
        DB = dBhelpUtil.getWritableDatabase();
        //开启事务
        DB.beginTransaction();


         //时间
        Date date = new Date();
        //格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //执行sql语句 方式
        String sql = "INSERT INTO tb_student(age,sex,name,clazz,createDate,logoHead) VALUES (?,?,?,?,?,?)";
        /**
         * sql 语句
         * 要插入的数据
         */
        DB.execSQL(sql,new Object[]{student.age,student.sex,student.name,student.clazz,simpleDateFormat.format(date),student.logoHead});

        //设置事务成功
        DB.setTransactionSuccessful();
        //添加事务
        DB.endTransaction();


    }

    //查询位图
    public Student selectBitmapById(Long id) {
        /** 获取一个读 操作数据的对象*/
        DB =dBhelpUtil.getReadableDatabase();
        Cursor cursor = null;


        /** 根据id 查询 返回一个游标对象
         * String sql,
         * String[] selectionArgs,
         * select * from tb_student where id = ?
         */
        cursor = DB.rawQuery("select * from "+ DBhelpUtil.TABLE_NAME+" where id =?",new String[]{id+""});
        // 解决报错；android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1
        CursorWindow cw = new CursorWindow("test", 5000000); // 设置CursorWindow的大小为5000000
        AbstractWindowedCursor ac = (AbstractWindowedCursor) cursor;
        ac.setWindow(cw);

        Student student = null;
        if(cursor != null){
            if(cursor.moveToNext()){
                student = new Student();
                // 根据游标找到列  在获取数据
                student.id = cursor.getLong(cursor.getColumnIndexOrThrow("id"));
                student.name = cursor.getString(cursor.getColumnIndexOrThrow(DBhelpUtil.TB_NAME));
                student.sex = cursor.getString(cursor.getColumnIndexOrThrow(DBhelpUtil.TB_SEX));
                student.age = cursor.getInt(cursor.getColumnIndexOrThrow(DBhelpUtil.TB_AGE));
                student.clazz = cursor.getString(cursor.getColumnIndexOrThrow(DBhelpUtil.TB_CLAZZ));
                student.creatDate = cursor.getString(cursor.getColumnIndexOrThrow(DBhelpUtil.TB_CREATEDATE));
                //图片
                student.logoHead =cursor.getBlob(cursor.getColumnIndexOrThrow("logoHead")) ;
            }
        }
        cursor.close();

        return student;
    }


    //按条件修改
    public int updateById(Student student,Long id){
        // 获取写操作数据库对象
        DB = dBhelpUtil.getWritableDatabase();
        //开启事务
        DB.beginTransaction();
        /**
         * String table,
         * ContentValues values, 数据行数据
         * String whereClause, 条件
         * String[] whereArgs   参数
         * 返回影响行数
         */
        //数据行数据
        ContentValues contentValues = new ContentValues();
        contentValues.put(DBhelpUtil.TB_NAME,student.name);
        contentValues.put(DBhelpUtil.TB_SEX,student.sex);
        contentValues.put(DBhelpUtil.TB_AGE,student.age);
        contentValues.put(DBhelpUtil.TB_CLAZZ,student.clazz);

        //时间
        Date date = new Date();
        //格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        contentValues.put(DBhelpUtil.TB_CREATEDATE, simpleDateFormat.format(date));

        int result = DB.update(DBhelpUtil.TABLE_NAME,contentValues,"id = ?", new String[]{id+""});
        //完成事务
        DB.setTransactionSuccessful();
        //结束事务
        DB.endTransaction();

       return result;
    }
}
